package com.ks.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

@SuppressWarnings({ "resource", "deprecation" })
public class SUtilCommon {
	
	private static Logger logger = LoggerFactory.getLogger(SUtilCommon.class);
	
	
	public static String doPostBodyData(String requestUrl, String bodyData) throws Exception {
    	HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(requestUrl);
        
        post.setHeader("Content-Type", "application/json");
        String result = "";
        
        try {
            StringEntity s = new StringEntity(bodyData, "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(s);

            // 发送请求
            HttpResponse httpResponse = client.execute(post);

            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            strber.append(line + "\n");
            inStream.close();

            result = strber.toString();
            
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                System.out.println("请求服务器成功，做相应处理");
            } else {
            	logger.error("请求服务端失败");
            }

        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        }
        return JSON.toJSONString(result);
    }
	
	
	/**
	 * 发起http get请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpGetRequest(String requestUrl) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(false);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e) {
			logger.error("地址请求失败[GET]："+requestUrl);
		} finally{
			if(httpUrlConn != null) httpUrlConn.disconnect();
		}
		return buffer.toString();
	}

	/**
	 * 发起http post请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpPostRequest(String requestUrl,String params) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(true);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("POST");
			
//			httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//			httpUrlConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
//			httpUrlConn.setRequestProperty("Charset", "UTF-8");
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			
			httpUrlConn.setConnectTimeout(1000);
			httpUrlConn.setReadTimeout(5 * 1000); 
			DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
			
			
			
			out.writeBytes(params.toString());
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.error("地址请求失败[POST]："+requestUrl + ";参数："+params);
		} finally{
			if(httpUrlConn != null) httpUrlConn.disconnect();
		}
		return buffer.toString();
	}
	
	
	public static String httpPostRequest3(String requestUrl,String params,String bodyJson) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(true);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("POST");
			
			httpUrlConn.setRequestProperty("Content-Type", "application/json");
			httpUrlConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			httpUrlConn.setRequestProperty("Charset", "UTF-8");
			
			httpUrlConn.setConnectTimeout(1000);
			httpUrlConn.setReadTimeout(5 * 1000); 
			DataOutputStream out = new DataOutputStream(httpUrlConn.getOutputStream());
			
			
			out.writeBytes(params.toString());
			out.writeBytes(bodyJson);
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.error("地址请求失败[POST]："+requestUrl + ";参数："+params);
		} finally{
			if(httpUrlConn != null) httpUrlConn.disconnect();
		}
		return buffer.toString();
	}
	
	
	/**
	 * 发起http post请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpPostRequest(String requestUrl,String params,Integer connectTimeout,Integer readTimeout) {
		StringBuffer buffer = new StringBuffer();
		URL url = null;
		HttpURLConnection httpUrlConn = null;
		try {
			 url = new URL(requestUrl);
			httpUrlConn = (HttpURLConnection) url
					.openConnection();
			// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
			// http正文内，因此需要设为true, 默认情况下是false;
			httpUrlConn.setDoOutput(true);
			// 设置是否从httpUrlConnection读入，默认情况下是true;
			httpUrlConn.setDoInput(true);
			// Post 请求不能使用缓存
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("POST");
			if(connectTimeout!=null){
				httpUrlConn.setConnectTimeout(connectTimeout);
			}
			if(readTimeout!=null){
				httpUrlConn.setReadTimeout(readTimeout); 
			}
			DataOutputStream out = new DataOutputStream(
					httpUrlConn.getOutputStream());
			out.writeBytes(params.toString());
			httpUrlConn.connect();
			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
		} catch (Exception e) {
			logger.error("地址请求失败[POST]："+requestUrl + ";参数："+params);
		} finally{
			if(httpUrlConn != null) httpUrlConn.disconnect();
		}
		return buffer.toString();
	}
	
	public static String httpPostRequest2(String requestUrl,String params) throws Exception {
		StringBuffer buffer = new StringBuffer();
		URL url = new URL(requestUrl);
		HttpURLConnection httpUrlConn = (HttpURLConnection) url
				.openConnection();
		// 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
		// http正文内，因此需要设为true, 默认情况下是false;
		httpUrlConn.setDoOutput(true);
		// 设置是否从httpUrlConnection读入，默认情况下是true;
		httpUrlConn.setDoInput(true);
		// Post 请求不能使用缓存
		httpUrlConn.setUseCaches(false);

		httpUrlConn.setRequestMethod("POST");
		DataOutputStream out = new DataOutputStream(
				httpUrlConn.getOutputStream());
		out.writeBytes(params.toString());
		httpUrlConn.connect();
		// 将返回的输入流转换成字符串
		InputStream inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(
				inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(
				inputStreamReader);
		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();
		// 释放资源
		inputStream.close();
		inputStream = null;
		httpUrlConn.disconnect();
		return buffer.toString();
	}

	public static String paramstourl(Map<String, Object> params) {
		StringBuilder sb = new StringBuilder();
		int i = 0;
		for (Iterator<Map.Entry<String, Object>> it = params.entrySet()
				.iterator(); it.hasNext();) {
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it
					.next();
			if (i > 0) {
				sb.append("&");
			}
			String value = "";
            try {
            	value = URLEncoder.encode(entry.getValue().toString(), "UTF-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
            sb.append(entry.getKey()+"="+value);
			i++;
		}
		return sb.toString();
	}

}
